<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'

import {
  useMessage,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NPopconfirm,
  NTreeSelect,
  NTag,
  NSwitch,
  NFlex,
  NAvatar,
  NSelect,
  NImage,
  NDataTable, NAlert,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import { router } from '@/router'
import default_image from '@/assets/images/mz.jpg'

defineOptions({ name: '订单管理' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '订单',
  initForm: {},
  doCreate: api.createOrdersList,
  doUpdate: api.updateOrdersListDD,
  doDelete: api.deleteOrdersList,
  refresh: () => $table.value?.handlerefresh(),
})
const isDisabled = ref(false)
const data = reactive({
  attributeOption: [
    {
      id: 1,
      name: '描述模板',
    },
    {
      id: 2,
      name: '规格模板',
    },
  ],
  sevendayOption: [
    {
      id: 0,
      name: '待接待',
      label: '待接待',
      value: 0,
    },
    {
      id: 1,
      name: '接待完成',
      label: '接待完成',
      value: 1,
    },
      {
      id: 2,
      name: '接待中',
        label: '接待中',
      value: 2,
    },
  ],
  state_option:[],
  uploadAction: base_path + 'api/goods/brand/file',
  token: getToken(),
  onLevelData:[],
  goodsType: [],
})


onMounted(() => {
  api.getOrdersType().then((res) => (data.state_option = res.data))
  api.getgoodsTypeArray().then((res) => (data.goodsType = res.data))
  $table.value?.handleSearch()
})

const columns = [
  {
    title: '+',
    width: 60,
    key: 'goods',
    align: 'center',
    type: 'expand',
    expandable: row => row.goods !== null,
    renderExpand: (row) => {
      let goods = row.goods ?? []
      let goods_columns=[
        {
          width:"60",
          title: 'ID',
          key: 'id'
        },
        {
          width:"auto",
          title: '商品',
          key: 'goods_name'
        },
          {
          width:"auto",
          title: '规格',
          key: 'sku_name'
        },
        {
          width:"80",
          title: '数量',
          key: 'num'
        },{
          width:"80",
          title: '价格',
          key: 'price'
        }
        // ,{
        //   width:"auto",
        //   title: '加料',
        //   key: 'attr_name'
        // }
      ]
      return h(NDataTable, { columns: goods_columns,striped:true ,size:"small",data:goods, style: { width: '1000px',margin:'10px 10px' }  })
    }
  },
  {
    title: 'ID',
    key: 'id',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '订单类型',
    key: 'type',
    align: 'center',
    width:100,
    ellipsis: { tooltip: true },
    render(row) {
      let tag = data.goodsType[row.type]
      if(row.is_give===1){
         tag = "抽奖赠送"
      }
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => tag }
      )
    },
  },
  {
    title: '下单人',
    key: 'user_name',
    width: 100,
    align: 'center',
    fixed: 'left',
    render(row) {
      return h(
        'div',
        {
          style: { whiteSpace: 'pre-line' }, // 允许换行
        },
        `${row.user_name}\n${row.user_phone}` // 使用换行符分隔
      );
    },
  },
    {
    title: '下单门店',
    key: 'address_name',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  {
    title: '实际付款',
    key: 'amount_price',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '抵扣金额',
    key: 'sale_price',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },

  {
    title: '订单状态',
    key: 'status_name',
    align: 'center',
    width:100,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => row.status_name }
      )
    },
  },
  {
    title: '接待状态',
    key: 'express_name',
    align: 'center',
    width:100,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => row.express_name }
      )
    },
  },
  {
    title: '付款时间',
    key: 'pay_time',
    width: '100',
    align: 'center',
  },


  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center',
    fixed: 'right',
        render(row) {
      let ret = []
      if(row.type===1&&row.status===1){
        ret.push(withDirectives(h(
                    NButton,{size: 'small',type: 'error',style: 'margin-right: 8px;',
                      onClick: () => {
                        on_edit(row)
                      },
                    },{
                      default: () => '接待',
                      icon: renderIcon('material-symbols:local-cafe-outline', {size: 16}),
                    }
                ),[[vPermission, 'post/api/content/category/update']]
        ))
      }
      if(1===1){
        ret.push(
          withDirectives(
                h(NButton,{size: 'small',type: 'primary',style: 'margin-right: 8px;',
                      onClick: () => {
                        on_more(row)
                      },
                    },{
                      default: () => '详情',
                      icon: renderIcon('material-symbols:assignment-add-outline-rounded', {size: 16}),
                    }
                ),[[vPermission, 'post/api/orders/orders/list']]
          )
      )
      }
      if(row.status===0){
        ret.push(
            withDirectives(
              h(
            NPopconfirm,
            {
              onPositiveClick: () => handle_success(row),
              onNegativeClick: () => {},
            },
            {
              trigger: () =>
                  withDirectives(
                      h(
                          NButton,
                          {
                            size: 'small',
                            type: 'success',
                            style: 'margin-right: 8px;'
                          },
                          {
                            icon: renderIcon('material-symbols:attach-money', { size: 16 }),
                          }
                      ),
                      [[vPermission, 'delete/api/content/category/delete']]
                  ),
              default: () => h('div', {}, '确定线下收款该订单吗?'),
            }
        ),
              [[vPermission, 'post/api/content/category/update']]
          ),
        )
      }
      if(row.status<2){
        ret.push(
            withDirectives(
              h(
            NPopconfirm,
            {
              onPositiveClick: () => handle_pass(row,4),
              onNegativeClick: () => {},
            },
            {
              trigger: () =>
                  withDirectives(
                      h(
                          NButton,
                          {
                            size: 'small',
                            type: 'error',
                          },
                          {

                            icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                          }
                      ),
                      [[vPermission, 'delete/api/content/category/delete']]
                  ),
              default: () => h('div', {}, '确定退款该订单吗?'),
            }
        ),
              [[vPermission, 'post/api/content/category/update']]
          ),
        )
      }

      return ret
    },
  },
]
const goods_columns=[
        {
          width:"auto",
          title: '商品',
          key: 'goods_name'
        },
      {
          width:"auto",
          title: '规格',
          key: 'sku_name'
        },
        {
          width:"80",
          title: '数量',
          key: 'num'
        },{
          width:"80",
          title: '价格',
          key: 'price'
        }
        // ,{
        //   width:"auto",
        //   title: '加料',
        //   key: 'attr_name'
        // }
      ]

async function handle_success(row){
  let ret = await api.updateOrdersSuccess({data_id:row.id})
  if(ret){
    $message?.success(ret.msg)
  }
  $table.value?.handlerefresh()
}

async function handle_pass(row,status) {
  let data = {
    order_id:row.id,
    order_status:status
  }
  await api.updateOrdersRefund(data)
  $table.value?.handlerefresh()
}


function on_edit(row) {
  handleEdit(row)
}

function on_more(row) {
  router.push({ path: '/orders/detail', query: { id: row.id } });
}

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}
async function  on_excel(){
  await api.onOrdersExcel({
    user_name:queryItems.value.user_name,
    status:queryItems.value.status,
    start_time:queryItems.value.start_time,
    end_time:queryItems.value.end_time
  })
  data.show_excel = true
  //$message?.success('正在生成下载文件,请前往下载中心查看')
}
function go_excel(){
  router.push({ path: '/downloads/list' });
}

</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="门店订单列表">

    <!-- 表格 -->
    <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :columns="columns"
        :get-data="api.getOrdersDDList"
        :scroll-x="1600"
    >
      <template #queryBar>
        <QueryBarItem label="客户姓名" :label-width="80">
          <NInput
              v-model:value="queryItems.user_name"
              clearable
              type="text"
              placeholder="请输入客户姓名"
              @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>
        <QueryBarItem label="支付状态" :label-width="80">
          <NSelect
              v-model:value="queryItems.status"
              style="width: 150px"
              :options="data.state_option"
              clearable
              placeholder="请选支付状态"
          />
        </QueryBarItem>
        <QueryBarItem label="付款时间" :label-width="70">
          <NDatePicker
              v-model:value="datetimeRange"
              type="datetimerange"
              clearable
              placeholder="请选择时间范围"
              @update:value="handleDateRangeChange"
          />
        </QueryBarItem>
        <QueryBarItem label="接待状态" :label-width="80">
          <NSelect
              v-model:value="queryItems.is_express"
              style="width: 150px"
              :options="data.sevendayOption"
              clearable
              placeholder="请选接待状态"
          />
        </QueryBarItem>
      </template>
    </CrudTable>
    <!-- 新增/编辑 弹窗 -->
    <CrudModal v-model:visible="modalVisible" title="接待信息" :loading="modalLoading" @save="handleSave" style="width: 800px">
      <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="80" :model="modalForm">
        <n-alert title="接待内容" type="success" style="margin-bottom: 10px" >
          <n-data-table :columns="goods_columns" :data="modalForm.goods" striped/>
<!--              温度&nbsp;:&nbsp;<n-tag style="margin-right: 10px">常温</n-tag>-->
<!--              甜度&nbsp;:&nbsp;<n-tag style="margin-right: 10px">半糖</n-tag>-->
<!--              其他备注&nbsp;:&nbsp;<n-tag>尽量做快点</n-tag><br>-->
        </n-alert>
        <n-radio-group
                v-model:value="modalForm.is_express"
                name="radiogroup"
                :default-value="0"
              >
                <n-space>
                  <n-radio v-for="item in data.sevendayOption" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </n-radio>
                </n-space>
              </n-radio-group>





      </NForm>
    </CrudModal>

  </CommonPage>
</template>
